import React,{Component} from 'react'
import Slider from 'react-slick';
import { Spin} from 'antd';
import * as pub from '../../config/public'
import * as fetch from '../../config/fetch'
import {message,Button} from 'antd'
import {Link,browserHistory} from 'react-router'
import Layer from '../Layer';
import $ from 'jquery'
const imgStyle = {
	width: '100%',
	height: '350px'
}
var timer;
class Banner extends Component {
	constructor(args) {
		super();

	}
	componentDidMount() {
		timer = setTimeout(()=>{
          this.slider.slickNext()
        },2000)
	}
	componentWillUnmount() {
		clearTimeout(timer)
	}
	render() {
		const settings = {
			speed: 500,
			autoplay: true,
			autoplaySpeed: 2000,
			rtl: false,
			dots: true,
			infinite: true,
			slidesToShow: 1,
			slidesToScroll: 1,
			nextArrow: <SampleNextArrowBanner />,
			prevArrow: <SamplePrevArrowBanner />
		};
		return (
			<Slider ref={c => this.slider = c } {...settings} className="banner">
               <div><img style={imgStyle} alt='test' src={require('../../style/images/banner-2.jpg')} /></div>
               <div><img style={imgStyle} alt='test' src={require('../../style/images/banner-1.jpg')} /></div>
               <div><img style={imgStyle} alt='test' src={require('../../style/images/banner-3.jpg')} /></div>
             </Slider>
		)
	}
}

class CourseCondition extends Component{
	constructor(props) {
		super(props);
		this.state = {
			categoriesList: []
		}
	}
	componentWillReceiveProps(nextProps) {
		this.setState({
			categoriesList: nextProps.categoriesList
		})
	}
	componentDidUpdate(prevProps, prevState) {
		$('.courseType').find('a').each(function(index, el) {
			let color = pub.getRandomColor();
			el.style.backgroundColor = color;
			$('head').append(`<style>#index_courseType${index}::before{ 
			    content: "";
                position: absolute;
                top: 0;
                left: -15px;
                width: 0;
                height: 0;
                border-top: 30px solid transparent;
                border-bottom: 30px solid transparent;
                border-right: 15px solid ${color};
            }</style>`);  
            $('head').append(`<style>#index_courseType${index}::after{ 
			    content: "";
                position: absolute;
                bottom: 0;
                right: -15px;
                width: 0;
                height: 0;
                border-top: 30px solid transparent;
                border-bottom: 30px solid transparent;
                border-left: 15px solid ${color};
            }</style>`); 
		});
	}
	render(){
		return(
          <div className="left-layout">
						<div className="study-center bg-FFFFFF box-shadow">
							<p>课程分类</p>
							<ul className="clearFix courseType" style={{whiteSpace:"nowrap",overflowX:"auto"}}>
                                {this.state.categoriesList.map((item,index)=>{
										return(
                                           <li key={index}>
									          <Link id={`index_courseType${index}`} to={"/LearnCenter/"+item.code}  className="hexagon hexagon-3">{item.name}</Link>
							        	   </li>
										)
									})}
							</ul>
			          </div>
		  </div>
		)
	}
}
class GoodStudents extends Component {
	constructor(args) {
		super();
		this.state = {
			personList: pub.getObject(0)
		}
	}
	render() {
		const {data} = this.props;

		return (
			<div className="panel-27 bg-FFFFFF box-shadow pad-l-20 pad-r-20">
					<div className="panel-27-head">
						<h3 className="title" style={{marginTop: '0'}}>本月优秀学员
                            <Link to='/StudentRank' style={{fontSize:'14px'}} className="floatR">更多&gt;</Link>
						</h3>
					</div>
					<ul className="index-rank">
					{data.map((item,index)=>{
						let ClassName;
						switch(index){
							case 0:ClassName='rank rank-one';break;
							case 1:ClassName='rank rank-two';break;
							case 2:ClassName='rank rank-three';break;
							default:ClassName='rank';break;
						}
						return(
							<li key={index}><span className={ClassName}>{index+1}</span><span>{item.userRealName}</span><span>{item.branchOffice}</span><span>{item.vipGradName}</span></li>
							)
					})}
					</ul>
		 </div>
		)
	}


}
class GoodArticle extends Component {
	constructor(args) {
		super();
		this.state = {
			articleList: pub.getObject(0),
			visibleDH:false,
			essayId:'',
			studyIntegral:'',
			loadBtning:false
		}
	}
	hideModelDH(){
			this.setState({
				visibleDH: false,
			});
	}
	ok(id){
		pub.loadBtning(this,true);
		fetch.cashEssay({essayId:id}).then((data)=>{
			if(data.result === 'RC100'){
				message.success(data.errMsg, 3)
				pub.jumpHistory.push("/ArticleDetail/" +id)
			}else{
				message.error(data.errMsg, 3);
			}
			pub.loadBtning(this,false);
		}, (res) => {
			pub.reject(res);
			pub.loadBtning(this,false);
		})
	}
	clickArticle(item) {
		if (item.goodEssay === '1') {
			if (item.userEssayOperation.isBuy === 1) {
				pub.jumpHistory.push("/ArticleDetail/" + item.essayId)
			} else {
				this.setState({
					visibleDH: true,
					essayId: item.essayId,
					studyIntegral: item.exchangeIntegral
				})
			}
		} else {
			pub.jumpHistory.push("/ArticleDetail/" + item.essayId)
		}
	}
	render() {
		const {data} = this.props;
		return (
			<ul className="index-article clearFix">
				{
					data.map((item, index) => {
						let essayPhotoPath = item.essayPhotos.length === 0 ? '' : item.essayPhotos[0].essayPhotoPath;
						return (
							<li key={index} className="have-img slider-item">
						
	
										<Link onClick={() => this.clickArticle(item)} >
											{item.essayPhotos.length > 0?<img alt='test' src={pub.getFile(essayPhotoPath)} />:null}
											<p className="title">{item.essayTitle?pub.subString(item.essayTitle,15):'没有标题'}</p>
											<p className="content">{item.essayNote?pub.subString(item.essayNote,50):'没有文字'}</p>
											<p className="time"><i className="icon-time"></i>{pub.formatTimestamp(item.createTime)}</p>
										</Link>
			
								{item.goodEssay === '1' ? <div className='index-jing' ></div> : null}
							</li>
						)
					})
				}
				<Layer
					title="设置兑换积分"
					show={this.state.visibleDH}
					hide={(e) => { this.setState({ visibleDH: false }) }}
					width="400px"
					height="270px"
				>
					<div className="row">
						<div className="pop-box-1" style={{ textAlign: 'left' }}>
							<p style={{ textAlign: 'center' }}>您需要{this.state.studyIntegral}积分兑换该文章</p>
						</div>
						<div className="pop-btn">
							<Button onClick={() => this.hideModelDH()} loading={this.state.loadBtning} className="btn btn-blue" style={{ borderRadius: '5px', marginRight: '50px' }}>取消</Button>
							<Button className="btn btn-blue" loading={this.state.loadBtning} style={{ borderRadius: '5px' }} onClick={() => this.ok(this.state.essayId)}>确认</Button>
						</div>
					</div>
				</Layer>
			</ul>
		)
	}

}

function SampleNextArrow(props) {
  const {onClick} = props
  return (
    <div
      className={"arr arr-right "}
      onClick={onClick}
    >
    <i className="icon-angle-right"></i>
    </div>
  );
}

function SamplePrevArrow(props) {
  const {onClick} = props
  return (
    <div
      className={"arr arr-left "}
      onClick={onClick}
    >
    <i className="icon-angle-left"></i>
    </div>
  );
}
//Banner
function SampleNextArrowBanner(props) {
  const {onClick} = props
  return (
    <div
      className={"arrBanner arr-right "}
      onClick={onClick}
    >
    <i className="icon-angle-right"></i>
    </div>
  );
}

function SamplePrevArrowBanner(props) {
  const {onClick} = props
  return (
    <div
      className={"arrBanner arr-left  "}
      onClick={onClick}
    >
    <i className="icon-angle-left"></i>
    </div>
  );
}
class GoodCourse extends Component {
	constructor(args) {
		super();
		this.state = {
			courseList: pub.getObject(0),
			courseId:'',
			studyIntegral:'',
			visibleEsDH:false,
			loadBtning:false
		}
	}
    hideModelDH(){
			this.setState({
				visibleEsDH: false,
			});
	}
	ok(id){
		pub.loadBtning(this,true);
		fetch.operateCourses(id).then((data)=>{
			if(data.result === 'RC100'){
				message.success(data.errMsg, 3);
				pub.jumpHistory.push("/CourseDetail/" +id);
			}else{
				message.error(data.errMsg, 3);
			}
			pub.loadBtning(this,false);
		}, (res) => {
			pub.reject(res);
			pub.loadBtning(this,false);
		})
	}
    componentWillReceiveProps(nextProps){
		this.setState({
            courseList:nextProps.data
		})
	}
	clickCourse(item) {
		if (item.goodCourse === '1') {
			if (item.userCourseOperation.isBuy === 1) {
				pub.jumpHistory.push("/CourseDetail/" + item.courseId)
			} else {
				this.setState({
					visibleEsDH: true,
					courseId: item.courseId,
					studyIntegral: item.studyIntegral
				})
			}
		} else {
			pub.jumpHistory.push("/CourseDetail/" + item.courseId)
		}
	}
	render(){
		const settings = {
			//dots: true,
			slidesToShow: this.state.courseList.length<5?this.state.courseList.length:5,
			slidesToScroll: 5,
			infinite: true,
			autoplay: false,
			nextArrow: <SampleNextArrow />,
			prevArrow: <SamplePrevArrow />
		};
		return(

			<div className='index-good-course' style={{marginBottom:"30px"}} >
			<div id="scrollbox" className="scroll-box">
					{this.state.courseList.length !== 0 ?
							<Slider {...settings} className="good-teacher">
								{this.state.courseList.map((item, index) => {
									return (
										<div key={index}>
											{
											<Link onClick={() => this.clickCourse(item)} >
											   <img alt='test' className="v-img" src={require("../../style/images/test.png")}/>
											   <div className="play"><i className="icon-play"></i></div>
										       {/*<video 
										       										             src={pub.getFile(item.coursevideoPath)}   
										       										             width="100%"  
										       										             height="100%" 
										       										             className="v-img"
										       										             >
										       										             您的浏览器不支持 video 标签。
										       									           </video>*/}
														<p><span>已点播{item.totalRecord}次</span>
															<span className="floatR">
																<i className="icon-heart"></i>
															</span></p>
														{item.goodCourse === '1' ? <div className='index-jing' ></div> : null}
											</Link>
											}
										</div>
									)
								})}
							</Slider>
						: null}
				<Layer
					title="设置兑换积分"
					show={this.state.visibleEsDH}
					hide={(e) => { this.setState({ visibleEsDH: false }) }}
					width="400px"
					height="270px"
				>
					<div className="row">
						<div className="pop-box-1" style={{ textAlign: 'left' }}>
							<p style={{ textAlign: 'center' }}>您需要{this.state.studyIntegral}积分兑换该课程</p>
						</div>
						<div className="pop-btn">
							<Button loading={this.state.loadBtning} onClick={() => this.hideModelDH()} className="btn btn-blue" style={{ borderRadius: '5px', marginRight: '50px' }}>取消</Button>
							<Button loading={this.state.loadBtning} className="btn btn-blue" style={{ borderRadius: '5px' }} onClick={() => this.ok(this.state.courseId)}>确认
								</Button>
						</div>
					</div>
				</Layer>
			   </div>
			   </div>
			)
	}
}

class Index extends Component {
	constructor(args) {
		super();

        this.state={
            loading:true,
            goodCourseList:[],
            goodStudentList:[],
            goodEssayList:[],
			categoriesList:[]
        }

	}
	classTypes(){
		fetch.goodType({pid:2}).then((data)=>{
			if (data.result === 'RC100') {
				this.setState({
					categoriesList: data.categoriesList?data.categoriesList:[],
				})
			} else {
				message.error(data.errMsg, 3);
				this.setState({
					categoriesList:[]
				})
			}
		},(res) => {
			this.setState({
					categoriesList:[]
		   })
			pub.reject(res);
		})
	}
	componentWillMount() {
		if(pub.user == null){
			pub.jumpHistory.push('/Login');
			return;
		}
		// if(pub.user.userType !== '讲师' && pub.user.userType !== '学员'){
		// 	pub.jumpHistory.push('/admin');
		// 	return;
		// }
		this.setState({
			loading: true
		});
		fetch.home().then((data) => {
			if (data.result !== 'RC100') {
				message.error(data.errMsg, 3);
				this.setState({
					loading: false
				});
			} else {
				this.setState({
					goodCourseList: data.goodCourseList,
					goodStudentList: data.goodStudentList,
					goodEssayList: data.goodEssayList
				}, () => {
					this.setState({
						loading: false
					});
				})
			}
		}, (res) => {
			this.setState({
				loading: false
			});
			pub.reject(res);
		})
		this.classTypes();
	}
	render() {
		return (
			<div className="wrapper bg-F0F4F6">
			  
			   <div className="layout clearFix" style={{paddingTop:'0px'}}>

			     <div className="row pad-t-20">
			       <Banner />
			     </div>
 
			     <div className="row">
			     	{/*<div className="index-title">
					</div>*/}
                  <Spin spinning={this.state.loading} tip="加载列表中...">
					<div className="left-layout">
					 <div className="index-title">
						<span>学习中心</span>
						<Link to='/LearnCenter' className="floatR">更多&gt;</Link>
					 </div>
					 <CourseCondition categoriesList={this.state.categoriesList}/>
			     	   	  <div className="index-title" style={{float:'left'}}>
							<span>精彩文章</span>
							<Link to='/GoodArticle' className="floatR">更多&gt;</Link>
					      </div>
					      <GoodArticle data={this.state.goodEssayList}/>
						<div className="index-title">
							<span>优秀课程</span>
							<Link to='/CourseRank' className="floatR">更多&gt;</Link>
						</div>
						<GoodCourse data={this.state.goodCourseList}/>
			     	</div>
			     	</Spin>

			     	<div className="right-layout" style={{paddingTop:'13px'}}>
                        <GoodStudents data={this.state.goodStudentList}/>
			     	</div>

			     </div>


			  </div>
			  
			</div>
		)
	}
}
export default Index